<?php

/**
 * 微信 Oauth SDK
 */

class wechatOauth {
    var $appid = "";
    var $appsecret = "";
    var $access_token = '';
    //构造函数，获取Access Token
    public function __construct($appid = NULL, $appsecret = NULL) {
        if($appid){
            $this->appid = $appid;
        }
        if($appsecret){
            $this->appsecret = $appsecret;
        }

        $mem = new Memcache;
        $mem->connect('127.0.0.1', 11211);// or die ("Memcache Could not connect");
        $prefix='star_wzma'.'WX_ACCESS_TOKEN'.'wzma';
        $data=$mem->get($prefix);
        if ($data){
            $data = unserialize($data);
            if ( $data['deadline'] >= time()) {
                $this->access_token= $data['access_token'];
            }
        }

        if ($this->access_token==''){//获取token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->https_request($url);
            $result = json_decode($res, true);
            $result['deadline']=time()+$result['expires_in']-5;
            $this->access_token = $result["access_token"];
            $mem->set($prefix, serialize($result));
        }
    }

    //获取用户基本信息
    public function get_user_info($info) {
        if($info['scope'] == 'snsapi_base') {
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$info['openid']."&lang=zh_CN";
        } else {
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$info['access_token']."&openid=".$info['openid']."&lang=zh_CN";
        }
        var_dump($url);

        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    //https请求
    public function https_request($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
